import React, { PureComponent } from 'react';
import {  Tree,Input,Icon } from 'antd';
import { Menu,Item,contextMenu } from 'react-contexify';
import 'react-contexify/dist/ReactContexify.min.css';
import { getNodeByKeyAndCallbackProcess } from '@/components/_utils/algorithmTools';
const { Search } = Input;
const { TreeNode } = Tree;
class AsyncLoadingTreeList extends PureComponent {
	state = {
	    expandedKeys: ['000000000000'],
	    autoExpandParent: true,
	    selectedKeys: [],
	    treeData: [],
	    selectedTreeByRightClick:"",
	   	searchValue: '',
	    dataList: [],
	    display: "block",
	};
    constructor(props) {
	    super(props);
    	this.state.treeData = [
	    	{ title: props.rootNodeName, key: '000000000000',levelcode:"000000000000" },
	    ]
	}
    
//展开收起
  	onExpand = expandedKeys => {
	    this.setState({
	      expandedKeys,
	      autoExpandParent: false,
	    });
  	};

  	onSelect = (selectedKeys, { node }) => {
    	const { checkedTreeChild } = this.props;
    	this.setState({ selectedKeys });
	   	checkedTreeChild(node);
  	};
  
  	addMenuTreeNode = () => {
		const { handleModalVisible } = this.props;
	    handleModalVisible(true,this.state.selectedTreeByRightClick,this.reLoadCurrentTreeNode);
	};
	
 	updateMenuTreeNode = () => {
  		const { handleUpdateModalVisible } = this.props;
	    handleUpdateModalVisible(true,this.state.selectedTreeByRightClick,this.reLoadCurrentTreeNodeUpdate);
	};
	
	viewMenuTreeNode = () => {
  		const { handleViewModalVisible } = this.props;
	    handleViewModalVisible(true,this.state.selectedTreeByRightClick);
	};
	
  	deleteMenuTreeNode = () => {
  		const { handleDeleteRecord } = this.props;
	    handleDeleteRecord(this.state.selectedTreeByRightClick,this.reLoadCurrentTreeNodeDelete);
	};
	
	RithtClickTreeNode = ({event,node}) => {
		event.preventDefault();
		contextMenu.show({
	      id: 'dept_id',
	      event: event,
	      props: {
	        foo: 'bar'
	      }
	    });
	    
	    if(node.props.dataRef.key != '000000000000') {
	  		this.setState({ 
				selectedTreeByRightClick: node,
				display:"block",
			});
	  	}else {
	  		this.setState({ 
				selectedTreeByRightClick: node,
				display:"none",
			});
	  	}
	}
	
	MyAwesomeMenu = () => (
		<Menu id='dept_id' theme="light" style={{zIndex: 1000}}>
	       <Item onClick={this.addMenuTreeNode}>
	       		<Icon type="plus-circle" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>添加</span>
	       </Item>
	       <Item onClick={this.updateMenuTreeNode} style={{display: this.state.display}}>
		       <Icon type="edit" style={{fontSize: 16,paddingTop: 3}}/>
		       <span style={{paddingLeft: 10}}>修改</span>
	       </Item>
	       <Item onClick={this.viewMenuTreeNode} style={{display: this.state.display}}>
		       <Icon type="file-search" style={{fontSize: 16,paddingTop: 3}}/>
		       <span style={{paddingLeft: 10}}>查看</span>
	       </Item>
	       <Item onClick={this.deleteMenuTreeNode} style={{display: this.state.display}}>
	       		<Icon type="delete" style={{fontSize: 16,paddingTop: 3}}/>
	       		<span style={{paddingLeft: 10}}>删除</span>
	       	</Item>
	    </Menu>
	);
	
  	onLoadData = (treeNode) => {
	    const { dispatch, treeList: { list },asyncLoadingTreeUrl } = this.props;
	    const params = {
	      parentid: treeNode.props.dataRef.key
	    };
	    return new Promise((resolve) => {
		    if (treeNode.props.children) {
		      resolve();
		      return;
		    }
	      dispatch({
	        type: asyncLoadingTreeUrl,
	        payload: params,
	        callback: () => {
	          const { treeList: { list } } = this.props;
	          treeNode.props.dataRef.children = list;
	          this.setState({
	          	treeData: [...this.state.treeData],
	          }); 
	          resolve();
	        }
	      });
	    });
	};
	
		
	reLoadCurrentTreeNode = (treeNode,dropKey) => {
       const data = [...this.state.treeData];
	   getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {
	        item.children = item.children || [];
	        // where to insert 示例添加到尾部，可以是随意位置
	        item.children.push(treeNode);
	    });

	   this.setState({
      		treeData: data,
       });

	};
	
	
	
	
    reLoadCurrentTreeNodeUpdate = (treeNode,currentTreeNodeKey,parentTreeNodeKey) => {
       const data = [...this.state.treeData];

	   getNodeByKeyAndCallbackProcess(data, currentTreeNodeKey,(item,index,arr) => {
	   		arr.splice(index,1);
	    });
	    
	   getNodeByKeyAndCallbackProcess(data, parentTreeNodeKey,(item) => {
	   		item.children = item.children || {};
	   		item.children.push(treeNode);
	    });
	  
	   this.setState({
      		treeData: data,
      });
   	}

	
	reLoadCurrentTreeNodeDelete = (currentTreeNodeKey) => {	

       const data = [...this.state.treeData];
	   getNodeByKeyAndCallbackProcess(data, currentTreeNodeKey,(item,index,arr) => {
	   		arr.splice(index,1);
	    });

	   this.setState({
      		treeData: data,
      });
    }

	onChange = e => {
		const { treeData,dataList } = this.state;
	    const { value } = e.target;
	    const expandedKeys = dataList
	      .map(item => {
	        if (item.title.indexOf(value) > -1) {
	          return this.getParentKey(item.title, treeData);
	        }
	        return null;
	      }).filter((item, i, self) => item && self.indexOf(item) === i);
	    this.setState({
	      expandedKeys,
	      searchValue: value,
	      autoExpandParent: true,
	    });
	};
	
	getParentKey = (title, tree) => {
	  let parentKey;
	  for (let i = 0; i < tree.length; i++) {
	    const node = tree[i];
	    if (node.children) {
	      if (node.children.some(item => item.title === title)) {
	        parentKey = node.key;
	      } else if (this.getParentKey(title, node.children)) {
	        parentKey = this.getParentKey(title, node.children);
	      }
	    }
	  }
	  return parentKey;
	};

	generateList = data => {
		
	  if( undefined == data ){ return false;}
	  
	  for (let i = 0; i < data.length; i++) {
	    const node = data[i];
	    const { key,title } = node;
	    this.state.dataList.push({ key, title: title });
	    if (node.children) {
	      this.generateList(node.children);
	    }
	  }
	};

	renderTreeNodes = data => {
		
		if( undefined == data ){ return false;}
			
		return data.map(item => {
		    	if(item.title) {
				    const index = item.title.indexOf(this.state.searchValue);
			        const beforeStr = item.title.substr(0, index);
			        const afterStr = item.title.substr(index + this.state.searchValue.length);
			        const title =
			          index > -1 ? (
			            <span>
			              {beforeStr}
			              <span style={{ color: '#f50' }}>{this.state.searchValue}</span>
			              {afterStr}
			            </span>
			          ) : (
			            <span>{item.title}</span>
			          );
				      if (item.children) {
				        return (
				    	    <TreeNode title={title} key={item.key} dataRef={item}>
					            {this.renderTreeNodes(item.children)}
					         </TreeNode>
				        );
				      }
				      return <TreeNode {...item} dataRef={item} title={title} key={item.key}/>;
		    	}
		});
	}
    
	onDrop = async ({event, node, dragNode, dragNodesKeys}) => {

		const levelcode = node.props.dataRef.levelcode;
		const dropKey = node.props.eventKey;
		const dragKey = dragNode.props.eventKey;
		const dragKey_parent_id = dragNode.props.dataRef.parentid;
		const new_levelcode = levelcode+"/"+dragKey;


		const data = [...this.state.treeData];


	   let dragObj;

	   getNodeByKeyAndCallbackProcess(data, dragKey,(item, index, arr) => {
	      arr.splice(index, 1);
	      dragObj = item;
	    });

	   /*getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {
	        item.children = item.children || [];
	        // where to insert 示例添加到尾部，可以是随意位置
	        item.children.push(dragObj);
	    });*/


		const { dispatch,updateTreeNodeBydragUrl } = this.props;
		const levecode = this.state.targetTreeLevelCode + "/" + dragNode.props.id;
		await dispatch({
	        type: updateTreeNodeBydragUrl,
	        payload:{
	        	source_parentid: dragKey_parent_id,
	        	source_id: dragKey,
	        	target_id: dropKey,
	        	levelcode: new_levelcode,
	        },
            callback: (response) => {
                     //持久化变拖拽时候使用
                getNodeByKeyAndCallbackProcess(data, dropKey,(item) => {
                    item.children = item.children || [];
                    // where to insert 示例添加到尾部，可以是随意位置
                    item.children.push(response.datarecord||{});
                });
            }
	  	});

	   await this.setState({
      		treeData: data,
       });

	  
	}
  render() {
	const { autoExpandParent,expandedKeys,selectedKeys,treeData } = this.state;
	const { searchTreePlaceholder } = this.props;
	this.generateList(treeData);
    return (
	    <div style={{float: 'left',width: '30%'}}>
	    	<Search style={{ marginBottom: 8,width: 200 }} placeholder={ searchTreePlaceholder } onChange={this.onChange} />
		    <Tree
	      	loadData={this.onLoadData}
	        onExpand={this.onExpand}
	        expandedKeys={expandedKeys}
	        autoExpandParent={autoExpandParent}
	        onSelect={this.onSelect}
	        selectedKeys={selectedKeys}
	        onRightClick={this.RithtClickTreeNode}
	        draggable
	        onDrop={this.onDrop}
	      	>
	        	{this.renderTreeNodes(treeData)}
	      	</Tree>
	      	{this.MyAwesomeMenu()}
	    </div>
    );
  }
}

export default AsyncLoadingTreeList;